/* eslint-disable keyword-spacing,indent */
// +----------------------------------------------------------------------
// | CmsWing [ 网站内容管理框架 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2115 http://www.cmswing.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: arterli <arterli@qq.com>
// +----------------------------------------------------------------------

module.exports = class extends think.cmswing.admin {
  constructor(ctx) {
    super(ctx); // 调用父级的 constructor 方法，并把 ctx 传递进去
    // 其他额外的操作
    this.tactive = 'fukuandan';
  }
  /**
   * index action
   * @return {Promise} []
   */
  indexAction() {
    // auto render template file index_index.html

    return this.display();
  }
  // 订单列表
  async listAction() {
    const status = this.get('status');
    const map = {};
    if (!think.isEmpty(status)) {
      try {
        map.status = JSON.parse(status);
      } catch (error) {
        map.status = status;
      }
      this.assign('status', status);
    }
    const q = this.get('q');
   if (!think.isEmpty(q)) {
     map['order_no|user_id|accept_name|mobile'] = ['like', q];
   }
    // this.config("db.nums_per_page",20)
    const data = await this.model('fukuandan').where(map).page(this.get('page') || 1, 20).order('id desc').countSelect();
    const html = this.pagination(data);
    this.assign('pagerData', html); // 分页展示使用
    // console.log(data.data);
    this.active = 'admin/fukuandan/list';
    this.assign('list', data.data);
    this.meta_title = '付款单管理';
    return this.display();
  }

  async fukuanlistAction() {
    const status = this.get('status');
    const map = {};
    if (!this.is_admin) {
      map.push_userid = this.user.id;
    }
    if (!think.isEmpty(status)) {
      try {
        map.status = JSON.parse(status);
      } catch (error) {
        map.status = status;
      }
      this.assign('status', status);
    }
    const q = this.get('q');
    if (!think.isEmpty(q)) {
      map['order_no|user_id|accept_name|mobile'] = ['like', q];
    }
    // this.config("db.nums_per_page",20)
    const data = await this.model('fukuandan').where(map).page(this.get('page') || 1, 20).order('id DESC').countSelect();
    const html = this.pagination(data);
    this.assign('pagerData', html); // 分页展示使用
    // console.log(data.data);
    this.active = 'admin/fukuandan/fukuanlist';
    this.assign('list', data.data);
    this.meta_title = '内勤付款管理';
    return this.display();
  }

  /**
   * 审核并分配业务内勤
   */
  async auditAction() {
    if (this.isPost) {
      const remarkData = this.post();
      const {
        id
      } = remarkData;
      remarkData.status = 1;
      const {
        remarksId,
        updateData
      } = await this.addremark();
      updateData.check_remarks_id = remarksId;
      updateData.shenheshijian = remarkData.remark_time;
      if (!think.isEmpty(remarksId)) {
        const res = await this.model('fukuandan').where({
          id: id
        }).update(updateData);
        if (res) {
          return this.success({
            name: '指定业务推送人员成功！'
          });
        } else {
          return this.fail('指定业务推送人员失败！');
        }
      } else {
        return this.fail('指定业务推送人员失败！');
      }
    } else {
      const id = this.get('id');
      this.assign('id', id);
      // const companyList = await this.model('zzjg').select();
      const userIds = await this.model('auth_user_role').where({
        role_id: ['in', [10, 11, 14]]
      }).getField('user_id');
      const users = await this.model('cmswing/member').where({
        id: ['in', userIds]
      }).select();
      const companyList = [];
      for (let index = 0; index < users.length; index++) {
        const element = users[index];
        const resIndex = companyList.findIndex((item) => {
          if(element.zzjginfo) {
            return item.id === element.zzjginfo.id;
          }else{
            return false;
          }
        });
        if (resIndex == -1) {
          if(element.zzjginfo) {
            companyList.push({
              id: element.zzjginfo.id,
              zzjg: element.zzjginfo.zzjg,
              userinfo: [{
                id: element.id,
                username: element.username,
                zzjg: element.zzjg
              }]
            });
          }
        } else {
          companyList[resIndex].userinfo.push({
            id: element.id,
            username: element.username,
            zzjg: element.zzjg
          });
        }
      }
      this.assign('companyList', companyList);
      this.meta_title = '内勤组织分配';
      return this.display();
    }
  }
  /**
     * 审核付款单
     */
  async fukuanauditAction() {
    if (this.isPost) {
      const id = this.post('id');
      const tjname = this.post('tjname');
      let resp;
      const shenheshijian = new Date().valueOf();
      const data = await this.model('fukuandan').where({id: id}).find();
      console.log('data=' + data);
      const memberdata = await this.model('member').where({id: data.shoukuan_id}).find();
      console.log('memberdata=' + memberdata);
      const action = 'fukuandan';
      try {
         const resdatary = await this.requestOA('executeQuery', { sql: `select id from hrmresource where lastname='${tjname}'` });
         if (resdatary && resdatary.errno == 0) {
           if (think.isEmpty(resdatary.data.list)) {
             return this.fail('OA无此员工！');
           }
         }else {
           return this.fail('接口调用失败！');
         }
         data.ygid = resdatary.data.list[0].id;
         data.nsrsbh = memberdata.nsrsbh;
         resp = await this.requestOA(action, data);
        console.log('resp=' + resp);
        if (resp.errno !== 0) { // 调用接口失败
          console.log('1+++++++++++++++++++++++++++++++++++++++++++');
          return this.fail(resp.errmsg + '[WS]');
        }
      } catch (e) {
        return this.fail('OA付款申请失败，请重试。[WS]');
        console.log('3+++++++++++++++++++++++++++++++++++++++++++');
      }
      const voids = await this.model('fukuandan').where({id: id}).update({status: 3, shenheshijian: shenheshijian});
      if (voids) {
        return this.success({name: '操作成功！', url: this.referer()});
      } else {
        return this.fail('操作失败！');
      }
    } else {
      const id = this.get('id');
      this.assign('id', id);
      this.meta_title = '审核付款单';
      return this.display();
    }
  }

  /**
     * 作废付款单
     */
  async voidAction() {
    if (this.isPost) {
      const id = this.post('id');
      const zuofei_remark = this.post('zuofei_remark');
      const shenheshijian = new Date().valueOf();
      const voids = await this.model('fukuandan').where({id: id}).update({status: 4, zuofei_remark: zuofei_remark, shenheshijian: shenheshijian});
      if (voids) {
        return this.success({name: '操作成功！', url: this.referer()});
      } else {
        return this.fail('操作失败！');
      }
    } else {
      const id = this.get('id');
      this.assign('id', id);
      this.meta_title = '退回付款单';
      return this.display();
    }
  }

  /**
     * 查看订单
     * @returns {*}
     */
  async seeAction() {
    const id = this.get('id');
     console.log(id);
    this.meta_title = '查看发布详情';
    // 获取发布信息
    const gongxufabu = await this.model('fukuandan').find(id);
    this.assign('fukuandan', fukuandan);
    const url = JSON.parse(fukuandan.tupian);
    this.assign('url', url);
    // 购买人信息
    const user = await this.model('member').where({id: gongxufabu.faburen}).find();
    this.assign('user', user);
    return this.display();
  }
};
